<template>
  <div class="mod-role">
    <el-form :inline="true" :model="dataForm" @keyup.enter.native="getDataList()">
      <el-form-item>
        <el-input size="mini" v-model="dataForm.roleName" placeholder="角色名称" clearable></el-input>
      </el-form-item>
      <el-form-item>
        <el-button size="mini" @click="getDataList()" icon="el-icon-search" type="success">查询</el-button>
        <el-button size="mini" v-if="isAuth('sys:role:save')" type="primary" @click="addOrUpdateHandle()" icon="el-icon-plus">新增</el-button>
        <el-button size="mini" v-if="isAuth('sys:role:delete')" type="danger" @click="deleteHandle()"
          :disabled="dataListSelections.length <= 0" icon="el-icon-delete">批量删除</el-button>
      </el-form-item>
    </el-form>
    <el-table :data="dataList" size="mini" v-loading="dataListLoading" @selection-change="selectionChangeHandle"
      style="width: 100%;" :header-cell-style="{ background: '#fcfcfc', color: '#606266', height:'36px'}">
      <el-table-column type="expand" header-align="center" align="center" width="50">
        <template slot-scope="scope">
          <el-row :class="[i1 != dataList.length - 1 ? 'box-bottom': '']" class="vcenger level1"
            v-for="(item1, i1) in scope.row.children" :key="item1.menuId">
            <!-- 一级权限 -->
            <el-col :span="4">
              <el-tag size="mini" @close="removeRightsById(scope.row, item1.menuId)" closable>{{ item1.name }}</el-tag>
              <i class="el-icon-caret-right"></i>
            </el-col>
            <!-- 二级与三级 -->
            <el-col :span="20">
              <el-row :class="[i2 === 0 ? '':'box-top']" class="vcenger" v-for="(item2,i2) in item1.children"
                :key="item2.menuId">
                <!-- 二级 -->
                <el-col :span="4">
                  <el-tag size="mini" @close="removeRightsById(scope.row, item2.menuId)" closable type="success">
                    {{ item2.name }}
                  </el-tag>
                  <i class="el-icon-caret-right"></i>
                </el-col>
                <!-- 三级 -->
                <el-col :span="18">
                  <el-tag size="mini" @close="removeRightsById(scope.row, item3.menuId)" closable
                    v-for="(item3) in item2.children" :key="item3.menuId" type="danger">{{ item3.name }}</el-tag>
                </el-col>
              </el-row>
            </el-col>
          </el-row>
        </template>
      </el-table-column>
      <el-table-column type="selection" header-align="center" align="center" width="50">
      </el-table-column>
      <el-table-column prop="roleId" header-align="center" align="center" width="80" label="ID">
      </el-table-column>
      <el-table-column prop="roleName" header-align="center" align="center" label="角色名称">
      </el-table-column>
      <el-table-column prop="roleSign" header-align="center" align="center" label="角色标记">
      </el-table-column>
      <el-table-column prop="remark" header-align="center" align="center" label="备注">
      </el-table-column>
      <el-table-column prop="createTime" header-align="center" align="center" width="180" label="创建时间">
      </el-table-column>
      <el-table-column fixed="right" header-align="center"  align="center" width="250" label="操作">
        <template slot-scope="scope">
          <el-button v-if="isAuth('sys:role:update')" type="text" size="mini"
            @click="addOrUpdateHandle(scope.row.roleId)">修改</el-button>
          <el-button v-if="isAuth('sys:role:delete')" type="text" size="mini" @click="deleteHandle(scope.row.roleId)">
            删除</el-button>
          <el-button v-if="isAuth('sys:role:set:menus')" type="text" size="mini" @click="openRightsDialog(scope.row)"> 分配权限
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination @size-change="sizeChangeHandle" @current-change="currentChangeHandle" :current-page="pageIndex"
      :page-sizes="[10, 20, 50, 100]" :page-size="pageSize" :total="totalPage"
      layout="total, sizes, prev, pager, next, jumper">
    </el-pagination>
    <!-- 弹窗, 新增 / 修改 -->
    <add-or-update v-if="addOrUpdateVisible" ref="addOrUpdate" @refreshDataList="getDataList"></add-or-update>

    <el-dialog v-drag title="分配权限" :visible.sync="setRightsDialogVisible" width="50%" @close="setRightsDialogClosed">
      <!-- 树形控件 展示权限 -->
      <el-tree show-checkbox :default-expand-all="false" node-key="menuId" :data="rightsList" :props="treeProps"
        :default-checked-keys="defaultCheckedKeys" ref="treeRef" @node-click="handleNodeClick"></el-tree>
      <span slot="footer" class="dialog-footer">
        <el-button @click="setRightsDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="allotRights">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
  import AddOrUpdate from './role-add-or-update'
  import {
    treeDataTranslate
  } from '@/utils'
  export default {
    data() {
      return {
        dataForm: {
          roleName: ''
        },
        dataList: [],
        pageIndex: 1,
        pageSize: 10,
        totalPage: 0,
        dataListLoading: false,
        dataListSelections: [],
        addOrUpdateVisible: false,
        setRightsDialogVisible: false,
        rightsList: [],
        treeProps: {
          children: 'children',
          label: 'name'
        },
        //默认选中值
        defaultCheckedKeys: [],
        //保存权限时使用的角色id
        roleId: null
      }
    },
    components: {
      AddOrUpdate
    },
    activated() {
      this.getDataList();
    },
    methods: {
      // 获取数据列表
      async getDataList() {
        this.dataListLoading = true
        const res = await this.$http({
          url: '/sys/role/list',
          method: 'get',
          params: this.$http.adornParams({
            'page': this.pageIndex,
            'limit': this.pageSize,
            'roleName': this.dataForm.roleName
          })
        })
        let data = res.data
        if (data && data.code === 0) {
          this.dataList = data.page.list
          this.dataList.forEach(item => {
            item.children = treeDataTranslate(item.children, 'menuId')
          })

          this.totalPage = data.page.totalCount
        } else {
          this.dataList = []
          this.totalPage = 0
        }
        this.dataListLoading = false
      },
      // 每页数
      sizeChangeHandle(val) {
        this.pageSize = val
        this.pageIndex = 1
        this.getDataList()
      },
      // 当前页
      currentChangeHandle(val) {
        this.pageIndex = val
        this.getDataList()
      },
      // 多选
      selectionChangeHandle(val) {
        this.dataListSelections = val
      },
      // 新增 / 修改
      addOrUpdateHandle(id) {
        this.addOrUpdateVisible = true
        this.$nextTick(() => {
          this.$refs.addOrUpdate.init(id)
        })
      },
      //删除权限
      async removeRightsById(role, menuId) {
        const confirmRes = await this.$confirm('确认要删除？', '提示', {
          confirmButtonText: '确认',
          cancelButtonText: '取消',
          type: 'warning'
        }).catch(err => err)

        if (confirmRes === 'confirm') {
          const res = await this.$http({
            url: `/sys/menu/delete/${role.roleId}/${menuId}`,
            method: 'post'
          })
          let obj = res.data
          if (obj && obj.code === 0) {
            this.$message.success('删除成功！')
            //重新给角色赋值
            role.children = treeDataTranslate(obj.data, 'menuId')
          } else {
            return this.$message.error('删除失败!');
          }
        } else {
          this.$msg.error('取消了删除！')
        }
      },
      // 删除
      deleteHandle(id) {
        let ids = id ? [id] : this.dataListSelections.map(item => {
          return item.roleId
        })
        this.$confirm(`确定对[id=${ids.join(',')}]进行[${id ? '删除' : '批量删除'}]操作?`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.$http({
            url: '/sys/role/delete',
            method: 'post',
            data: this.$http.adornData(ids, false)
          }).then(({
            data
          }) => {
            if (data && data.code === 0) {
              this.$message({
                message: '操作成功',
                type: 'success',
                duration: 1500,
                onClose: () => {
                  this.getDataList()
                }
              })
            } else {
              this.$message.error(data.msg)
            }
          })
        }).catch(() => {})
      },
      async openRightsDialog(role) {
        this.roleId = role.roleId
        //加载权限
        this.getRightsList()
        //获取默认的menuId
        this.getDefaultCheckKeys(role, this.defaultCheckedKeys)
        //显示
        this.setRightsDialogVisible = true
      },
      async getRightsList() {
        const res = await this.$http({
          url: '/sys/menu/list',
          method: 'get',
          params: this.$http.adornParams()
        })
        this.rightsList = treeDataTranslate(res.data, 'menuId')
      },
      setRightsDialogClosed() {
        this.roleId = null,
        this.defaultCheckedKeys = []
      },
      handleNodeClick() {

      },
      //分配权限
      async allotRights(){
        const ids = [
          ...this.$refs.treeRef.getCheckedKeys(),
          ...this.$refs.treeRef.getHalfCheckedKeys()
        ]
        // const menuIds = keys.join(",")
        const res = await this.$http({
          url: `/sys/role/updateRights/${this.roleId}`,
          method: 'post',
          data: this.$http.adornData(ids, false)
        })
        const data = res.data
        if(data && data.code === 0){
          this.$message.success("保存成功！");
          this.getDataList()
          this.setRightsDialogVisible = false
        }else{
          this.$message.error("保存失败！");
        }

      },
      getDefaultCheckKeys(node, arr){
        //如果是第三级
        if(!node.children){
          return arr.push(node.menuId)
        }
        node.children.forEach(item => {
          this.getDefaultCheckKeys(item, arr)
        })
      },
      async getDefaultCheckKeys2(){
        //获取当前roleId对应的menuId
        const res = await this.$http({
          url: `/sys/role/getMenuIdList/${role.roleId}`,
          method: 'get'
        })
        let obj = res.data
        if (obj && obj.code === 0) {
          this.defaultCheckedKeys = obj.data
        }
      },
    }
  }
</script>

<style lang="less" scope>
  .el-tag {
    margin: 7px 7px 7px 10px;
  }

  .level1 {
    margin-left: 40px;
  }

  .box-top {
    border-top: 1px solid #eeeeee;
    padding: 2px 0;
  }

  .box-bottom {
    border-bottom: 1px solid #eeeeee;
  }

  .vcenger {
    display: flex;
    align-items: center;
  }
</style>
